<!-- 登录页面 -->
<template>
<div class='admin-login'>
   <div class="warp">
       <h1>教务管理系统</h1>
      <el-form :model="formData" :rules="rules" ref="submitForm">
        <el-form-item prop="username">
          <el-input v-model="formData.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="formData.password" type="password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" class="login-button" @click="submitLogin('submitForm')">登录</el-button>
        </el-form-item>
      </el-form>
      <div class="login-tip">
        <p>温馨提示</p>
        <p>未登录过的新用户，自动注册</p>
        <p>注册过的用户可凭账号密码登录</p>
      </div>
   </div>
   <div :class="['mask',{none:isShow}]"></div>
   <div :class="['verify',{none:isShow}]">
       <h3><span>请输入正确的验证码：</span><i class="el-icon-circle-close" @click="close"></i></h3>
       <div class="content">
            <label for="code">验证码：</label>
            <input type="text" name="" v-model="inpCode" id="code" placeholder="请输入验证码">
            <span>{{ spanCode }}</span><a href="javascript:;" @click="changeCode">看不清</a>
            <p>
                <el-button type="primary" class="go" round @click="success">确定</el-button>
                <el-button type="danger" class="out" round @click="close">取消</el-button>
            </p>
       </div>
   </div>
</div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import CryptoJS from 'crypto-js'; //用于登陆时对密码进行加密
import getRandChar from "../api/func.js";
export default {
//import引入的组件需要注入到对象中才能使用
components: {},
data() {
//这里存放数据
return {
     formData: {
        username: "",
        password: "",
      },
      rules:{
          username:[{required: true,message: "输入用户名有误",trigger: "blur"}],         
          password:[{ required: true, message: "输入密码不能为空", trigger: "blur" }]
      },
      isShow:true,
      spanCode:'',
      inpCode:'',
};
},
//监听属性 类似于data概念
computed: {},
//监控data中的数据变化
watch: {},
//方法集合
methods: {
    submitLogin(name){
        this.$refs[name].validate( (valid) => {
            if(valid){
                let username = this.formData.username;
                let password = this.formData.password;
                password = CryptoJS.HmacSHA1(password, "Key").toString();
                this.$http.post("http://linweiqin.cn:8001/admin/login",{
                user_name:username,
                password:password
                }).then( res => {
                    // console.log(res);
                    if(res.status === 1 && res.success === "注册管理员成功"){
                        alert("注册管理员成功~");
                    }else if(res.status === 1 && res.success === "登录成功"){
                        //弹出验证框
                        this.isShow = false;
                    }else if(res.status === 0){
                         this.$message.error('该用户已存在，密码输入错误');
                    }
                })
            }
            
        })
    },
    // 更换验证码
    changeCode(){
        this.spanCode = getRandChar();
    },
    // 关闭验证框
    close(){
        this.isShow = true;
        this.inpCode = '';
    },
    // 确定登录
    success(){
        if(this.inpCode == this.spanCode){
            this.inpCode ='';
             // vuex 同步修改 状态中的数据
            this.$store.commit("LOGIN",1);
            // console.log(this.$store.state.status);
            document.cookie = "username = " + this.formData.username;
            //切换页面
            // console.log(document.cookie);
            this.$router.push('layout');  
        }else{
            this.$message.error('验证码错误，请重新输入');
            this.inpCode = '';
            this.spanCode = getRandChar();//重新生成验证码
        }
    }
},
//生命周期 - 创建完成（可以访问当前this实例）
created() {
    function getCookie(key){
        let str = "";
        var tmp = document.cookie.split('; ');
        for(var i=0;i<tmp.length;i++){
            var t = tmp[i].split('=');
            if(t[0]===key){
                str = t[1];
            }
        }
        return str;   
    }
    function setCookie(key,value,expires){
        if(expires){
            var time = new Date();
            time.setTime(time.getTime()-8*60*60*1000 + 1000*expires);
            document.cookie = key+"="+value+";expires="+time;
        }else{
            document.cookie = key+"="+value;
        }
    }
    if(getCookie('username')){
        this.$message({
            message: '退出成功',
            type: 'success'
        });
        this.$store.commit("LOGOUT",0);
        setCookie('username','',-1);
    }
},
//生命周期 - 挂载完成（可以访问DOM元素）
mounted() {
	//  在初始化的时候先随机给span里面生成一串字符
	this.spanCode = getRandChar();
},
beforeCreate() {}, //生命周期 - 创建之前
beforeMount() {}, //生命周期 - 挂载之前
beforeUpdate() {}, //生命周期 - 更新之前
updated() {}, //生命周期 - 更新之后
beforeDestroy() {}, //生命周期 - 销毁之前
destroyed() {}, //生命周期 - 销毁完成
activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style  lang="less" scoped>
.admin-login{
    width: 100vw;
    height: 100vh;
    background: #2d3a4b;
    .warp{
        width: 480px;
        margin: 0 auto;
        padding: 160px 35px 0;
        h1{
            font-size: 26px;
            color: #eee;
            margin: 0 auto 40px auto;
            text-align: center;
            font-weight: 700;
        }
        .login-button{
            width: 100%;
        }
        .login-tip{
            color: #f00;
            text-align: center;
            line-height: 26px;
            margin-top: 10px;
        }
    }
    .mask{
        // display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0,0,0,0.5);
        z-index: 5;
    }
    .verify{
        // display: none;
        position: fixed;
        width: 550px;
        height: 200px;
        border: 1px solid #ccc;
        border-radius: 10px;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        margin: auto;
        background: #fff;
        z-index: 6;
        h3{
            height: 50px;
            padding: 0 15px;
            display: flex;
            justify-content: space-between;
            align-content: center;
            line-height: 50px;
            border-bottom: 1px solid #ccc;
            span{
                color: #67C23A;
                font-style: italic;
                
            }
            i{
                margin-top: 10px;
                font-size: 30px;
                color: #F56C6C;
                cursor: pointer;
            }
            i:hover{
                opacity: 0.7;
            }
        }
        .content{
            padding: 40px 15px 0 50px;
            label{
                color: salmon;
                font-size: 20px;
            }
            #code{
                width: 200px;
                padding: 0 20px;
                border: 1px solid #ccc;
                height: 30px;
                border-radius: 6px;
                margin-right: 20px;
                outline-color:#03edf9 ;
            }
            span{
                display: inline-block;
                 width: 80px;
                 font-style: italic;
                  height: 30px;
                  border: 1px solid #E6A23C;
                  border-radius: 5px;
                  vertical-align: middle;
                  margin-right: 10px;
                  background: #E6A23C;
                  text-align: center;
                  line-height: 30px;
                  color: #f00;
            }
            a{
                vertical-align: bottom;
            }
            .go{
                margin: 20px 30px 0 120px;
            }
            .out{
                margin-top: 20px;
            }
        }
    }
    .none{
        display: none;
    }
}
    
</style>